package com.yunhoo.sys.navigation;

import com.yunhoo.sys.util.common.FacesUtils;
import com.yunhoo.sys.util.common.LoginParam;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.faces.FacesException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.richfaces.model.TreeNode;

@ManagedBean(name = "sysmenu")
@SessionScoped
public class MenuBean implements Serializable {

    private TreeNode rootNode = null;
    private String selectedPageUrl = "/welcome.xhtml";
    private int flag = 1;
    //
    private List<MenuItem> menuItemList = null;
    //
    private boolean isTree = false;
    //
    private String currentRole = "";

    private void addNodes(String path, TreeNode node, Properties properties) {
        boolean end = false;
        int counter = 1;
        while (!end) {
            String key = path != null ? path + '.' + counter : String.valueOf(counter);
            String value = properties.getProperty(key);
            if (value != null) {
                MenuTreeNodeImpl nodeImpl;
                String[] menu = value.split(" +");
                if (menu.length == 2) {
                    if (menu[1] != null && !menu[1].isEmpty()) {
                        nodeImpl = new MenuTreeNodeImpl(true, menu[0]);
                        nodeImpl.setUrl(menu[1]);
                    } else {
                        nodeImpl = new MenuTreeNodeImpl(false, menu[0]);
                    }
                } else {
                    nodeImpl = new MenuTreeNodeImpl(false, value);
                }
                node.addChild(String.valueOf(flag), nodeImpl);
                flag += 1;
                addNodes(key, nodeImpl, properties);
                counter++;
            } else {
                end = true;
            }
        }
    }

    private void addMenuItem(String path, List<MenuItem> itemList, Properties properties) {
        boolean end = false;
        int counter = 1;
        while (!end) {
            String key = path != null ? path + '.' + counter : String.valueOf(counter);
            String value = properties.getProperty(key);
            if (value != null) {
                MenuItem nodeImpl;
                String[] menu = value.split(" +");
                if (menu.length == 2) {
                    if (menu[1] != null && !menu[1].isEmpty()) {
                        nodeImpl = new MenuItem();
                        nodeImpl.setIsEnd(true);
                        nodeImpl.setName(menu[0]);
                        nodeImpl.setUrl(menu[1]);
                    } else {
                        nodeImpl = new MenuItem();
                        nodeImpl.setIsEnd(false);
                        nodeImpl.setName(menu[0]);
                    }
                } else {
                    nodeImpl = new MenuItem();
                    nodeImpl.setIsEnd(false);
                    nodeImpl.setName(value);
                }
                itemList.add(nodeImpl);
                nodeImpl.setSubList(new ArrayList<MenuItem>());
                List<MenuItem> subList = nodeImpl.getSubList();
                addMenuItem(key, subList, properties);
                counter++;
            } else {
                end = true;
            }
        }
    }

    public void loadWithTree() {
        isTree = !isTree;
    }

    public String getNavigationUrl() {
        if (isTree) return "/template/navigation_tree.xhtml";
        else return "/template/navigation.xhtml";
    }

    private void printMenuItem(List<MenuItem> itemli) {
        for (MenuItem item : itemli) {
            System.out.println("name : " + item.getName() + " - url: " + item.getUrl());
            if (!item.isIsEnd()) {
                printMenuItem(item.getSubList());
            }
        }
    }

    private String getTreePath() {
        //String currentRole = LoginParam.getPer().getRole().trim();
        String treePath = "";
        //System.out.println("current role : " + currentRole);
        //普通职工 -- E -- personal.data
        //管理员 -- A -- admin.data
        //部门负责人 -- D -- deptAdmin.data
        //资产 -- ZC -- admin_zichang.data
        //工会 -- GH -- admin_huifei.data
        //党委 -- DW -- admin_dangfei.data
        //财务 -- CW -- admin_caiwu
        //游客 -- YK -- guest.data
        if (currentRole.equalsIgnoreCase("E")) {
            treePath = "/admin_ssf/personal.data";//普通职工
        } else if (currentRole.equalsIgnoreCase("A")) {
            treePath = "/admin_ssf/admin.data";//管理员
        } else if (currentRole.equalsIgnoreCase("C")) {
            treePath = "/admin_ssf/admin_caiwu.data";//财务(原为CW,测试改为C)
        } else if (currentRole.equalsIgnoreCase("P")) {
            treePath = "/admin_ssf/admin_chuna.data";//出纳(测试)
        }
        return treePath;
    }

    private void loadTree_E() {
        String treepath = getTreePath();
        if (treepath.isEmpty()) {
            return;
        }
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        InputStream dataStream = externalContext.getResourceAsStream(treepath);
        //BufferedReader in = new BufferedReader(new InputStreamReader(dataStream));
        try {
            Properties properties = new Properties();
            properties.load(dataStream);
            for (Map.Entry entry : properties.entrySet()) {
                String value = (String) entry.getValue();
                String str2 = new String(value.getBytes("iso-8859-1"), "utf-8");
                entry.setValue(str2);
            }
            menuItemList = new ArrayList<MenuItem>();
            addMenuItem(null, menuItemList, properties);
        } catch (IOException e) {
            throw new FacesException(e.getMessage(), e);
        } finally {
            if (dataStream != null) {
                try {
                    dataStream.close();
                } catch (IOException e) {
                    externalContext.log(e.getMessage(), e);
                }
            }
        }
    }

    private void loadTree() {
        String treepath = getTreePath();
        if (treepath.isEmpty()) {
            return;
        }
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        InputStream dataStream = externalContext.getResourceAsStream(treepath);
        //BufferedReader in = new BufferedReader(new InputStreamReader(dataStream));
        try {
            Properties properties = new Properties();
            properties.load(dataStream);
            for (Map.Entry entry : properties.entrySet()) {
                String value = (String) entry.getValue();
                String str2 = new String(value.getBytes("iso-8859-1"), "utf-8");
                entry.setValue(str2);
            }
            rootNode = new MenuTreeNodeImpl();
            addNodes(null, rootNode, properties);
        } catch (IOException e) {
            throw new FacesException(e.getMessage(), e);
        } finally {
            if (dataStream != null) {
                try {
                    dataStream.close();
                } catch (IOException e) {
                    externalContext.log(e.getMessage(), e);
                }
            }
        }
    }

    public TreeNode getRootNode() {
        if (roleChanged() || rootNode == null) {
            System.out.println("getRootNode loadTree");
            loadTree();
        }
        return rootNode;
    }

    public List<MenuItem> getMenuItemList() {
        if (roleChanged() || menuItemList == null) {
            //System.out.println("getMenuItemList --> loadTree_E()");
            loadTree_E();
            //printMenuItem(menuItemList);
        }
        return menuItemList;
    }

    private boolean roleChanged() {
        String role = LoginParam.getPer().getRole().trim();
        boolean changed = false;
        if (!currentRole.equals(role)) {
            currentRole = role;
            changed = true;
        }
        return changed;
    }

    public String getSelectedPageUrl() {
        String requestPage = FacesUtils.getRequestParameter("contentPage");
        if (requestPage != null && !requestPage.isEmpty()) {
            selectedPageUrl = requestPage;
        }
        return selectedPageUrl;
    }

    public void setSelectedPageUrl(String selectedPageUrl) {
        this.selectedPageUrl = selectedPageUrl;
    }

    public void initSelectedPage() {
        selectedPageUrl = "/welcome.xhtml";
    }
}
